﻿#include "demuxthread.h"
#include <QDebug>

DemuxThread::DemuxThread(QObject *parent)
    : QThread{parent}
{
    demux = new Demux;
    videoThread = new VideoThread;
    videoThread->setObjectName("videoThread");
    audioThread = new AudioThread;
    audioThread->setObjectName("audioThread");
}

DemuxThread::~DemuxThread()
{
    exit_flag = true;
    qDebug() << "~DemuxThread() ---- wait();";
    //等待当前线程结束
    wait();
    if(demux)
    {
        delete demux;
    }
}

bool DemuxThread::open(const char *url)
{
    bool ret = demux->open_stream(url);
    if(!ret)
    {
        return false;
    }

    int index = -1;
    index = demux->getVideoStreamIndex();
    if(index >= 0)
    {
        AVCodecParameters * v_codec_params = demux->copyAVCodecParameters(index);
        videoThread->openVideoDecoder(v_codec_params,1,1);
        if(v_codec_params == NULL)
        {
            qDebug() << "AVCodecParameters * v_codec_params = demux.copyAVCodecParameters(VIDEO_TYPE); ----- error";
            return false;
        }
    }
    return true;
}

void DemuxThread::start_all_thread()
{
    QThread::start();//启动当前线程
    videoThread->start();
    audioThread->start();
}

void DemuxThread::run()
{
    while (!exit_flag)
    {
        // mutex.lock();
        if (!demux)
        {
            // mutex.unlock();
            msleep(5);
            continue;
        }
        AVPacket *pkt = demux->read();
        if (!pkt)
        {
            // mutex.unlock();
            msleep(5);
            continue;
        }

        //判断数据是音频
        if (pkt->stream_index == demux->getAudioStreamIndex())
        {
            //放入缓冲队列中
            if(audioThread) {
                audioThread->addList(pkt);
            }
        }
        else if(pkt->stream_index == demux->getVideoStreamIndex())//视频
        {
            //放入缓冲队列中
            if (videoThread) {
                videoThread->addList(pkt);
            }
        }else
        {
            qDebug() << "unknown pkt type";
        }
    }
}
